import React from 'react'
import ReactDOM from 'react-dom'
import { listShops, newShop, closeShop, openShop, getShop, editShop, blockAdd, blockRemove, itemRemove, itemAdd, itemEdit, itemGet } from '../../api/business'
import AppBar from '../../components/AppBar'
import { CItem } from '../../components/CItem'
import { Formik, Field, Form } from 'formik';
import Select from 'react-select'
import { SelectMap } from '../../components/Map';

export class BusinessShops extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shopList: []
        };
    }

    componentDidMount() {
        listShops((data) => {

            this.setState({
                shopList: data
            })
        })
    }

    render() {
        let shops = this.state.shopList.map((shop) => {
            return <div className="card" style={{ margin: '10px 0' }} key={shop.id}>

                <div className="card-body">
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <strong>{shop.name}</strong>
                        <small>{shop.description}</small>
                        <small>起送 ￥{shop.startPrice}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;配送 ￥{shop.shipPrice}</small>
                    </div>
                </div>
                <div className="card-footer" style={{ display: 'flex' }}>
                    {shop.working
                        ? <button onClick={() => { closeShop(shop.id) }} className="btn btn-block btn-danger" style={{ flex: 1 }}>打烊</button>
                        : <button onClick={() => { openShop(shop.id) }} className="btn btn-block btn-success" style={{ flex: 1 }}>开始营业</button>}
                    <button onClick={() => { this.props.history.push({ pathname: '/business/shop/' + shop.id }) }} className="btn btn-primary" disabled={shop.working} style={{ flex: 1 }}>编辑店铺</button>
                    <button onClick={() => { this.props.history.push({ pathname: '/business/orders/' + shop.id }) }} className="btn btn-light" style={{ flex: 1 }}>店铺订单</button>
                </div>
            </div>
        })
        return (
            <div>
                <AppBar></AppBar>
                <div className="container" style={{ padding: '15px 0' }}>
                    <button onClick={() => { this.props.history.push({ pathname: '/business/addshop' }) }} className="btn btn-block btn-lg btn-warning">+ 新增店铺</button>
                    <div className="row">
                        <div className="col-12">
                            {shops}
                        </div>
                    </div>
                </div>
            </div >
        );
    }
}

export class EditShop extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            shop: {
                id: this.props.match.params.id,
                name: '',
                description: '',
                startPrice: 0.0,
                shipPrice: 0.0,
                blocks: [],
                rate: 0.0
            },
            blockName: ''
        }
        this.editDescription = this.editDescription.bind(this)
        this.submitChange = this.submitChange.bind(this)
        this.editShipPrice = this.editShipPrice.bind(this)
        this.editStartPrice = this.editStartPrice.bind(this)
        this.removeBlock = this.removeBlock.bind(this)
        this.editBlockName = this.editBlockName.bind(this)
    }

    componentDidMount() {
        getShop(this.props.match.params.id, (data) => {
            this.setState({
                shop: data
            })
        })
    }

    editDescription(event) {
        let newValue = event.target.value

        this.setState((prevState, props) => {
            let shop = prevState.shop
            shop.description = newValue
            return ({
                shop: shop
            })
        })
    }

    editStartPrice(event) {
        let newValue = event.target.value

        this.setState((prevState, props) => {
            let shop = prevState.shop
            shop.startPrice = newValue
            return ({
                shop: shop
            })
        })
    }

    editShipPrice(event) {
        let newValue = event.target.value

        this.setState((prevState, props) => {
            let shop = prevState.shop
            shop.shipPrice = newValue
            return ({
                shop: shop
            })
        })
    }

    submitChange() {
        let shop = this.state.shop
        editShop(shop.id, shop.contact, shop.startPrice, shop.shipPrice, shop.description)
    }

    editBlockName(event) {

        this.setState({
            blockName: event.target.value
        })
    }

    addBlock() {
        if (this.state.blockName != '') {
            blockAdd(this.state.shop.id, this.state.blockName)
        }
    }

    removeBlock(id) {
        blockRemove(id)
    }

    itemRemove(id) {
        itemRemove(id)
    }

    render() {
        let navLinkActive = false;
        const blocks = this.state.shop.blocks.map((block) => {
            const elm = <li className="nav-item" key={"#" + block.name} style={{ display: 'flex' }}>
                <a className={navLinkActive ? 'nav-link' : 'nav-link active'} href={"#" + block.name} style={{ textAlign: 'center', flex: '1' }}>
                    {block.name}
                </a>
                <button className="btn btn-outline-danger" onClick={() => { this.removeBlock(block.id) }}>删除</button>
            </li>;
            navLinkActive = true;
            return elm;
        });

        const comms = this.state.shop.blocks.map((block) => {
            const cs = block.commodities.map((c) => {
                return (
                    <div
                        key={"citem-" + c.id}>
                        <CItem
                            item={c}
                            disableAdd={true}
                        ></CItem>
                        <button onClick={() => { this.props.history.push({ pathname: '/business/comm/' + c.id, query: { comm: c } }) }} className="btn btn-outline-warning">编辑</button>
                        <button onClick={() => { this.itemRemove(c.id) }} className="btn btn-outline-danger">删除</button>
                    </div>
                );
            });
            return (
                <div id={block.name} key={"block-page-" + block.id} style={{ marginTop: '20px' }}>
                    <small style={{ fontWeight: 'bold' }}>{block.name}</small>
                    {cs}
                </div>
            );
        });

        return (
            <>
                <AppBar></AppBar>
                <div className="container-fluid" style={{ padding: '20px 10px' }}>
                    <div className="jumbotron">
                        <h1>{this.state.shop.name}</h1>
                        <span>
                            <div className="input-group">
                                <input className="form-control" onChange={this.editDescription} value={this.state.shop.description}></input>
                                <div className="input-group-append">
                                    <button className="btn btn-primary" type="button" onClick={() => { this.submitChange() }}>修改</button>
                                </div>
                            </div>
                        </span>
                        <span>
                            <div className="input-group">
                                <div className="input-group-prepend">
                                    <span className="input-group-text">起送费</span>
                                </div>
                                <input type="number" className="form-control" onChange={this.editStartPrice} value={this.state.shop.startPrice}></input>
                                <div className="input-group-append">
                                    <button className="btn btn-primary" type="button" onClick={() => { this.submitChange() }}>修改</button>
                                </div>
                            </div>
                        </span>
                        <span>
                            <div className="input-group">
                                <div className="input-group-prepend">
                                    <span className="input-group-text">配送费</span>
                                </div>
                                <input type="number" className="form-control" onChange={this.editShipPrice} value={this.state.shop.shipPrice}></input>
                                <div className="input-group-append">
                                    <button className="btn btn-primary" type="button" onClick={() => { this.submitChange() }}>修改</button>
                                </div>
                            </div>
                        </span>
                    </div>
                    <div className="row">
                        <nav className="col-3" id="block-scroll-spy">
                            <button className="btn btn-block btn-success" data-toggle="modal" data-target="#modal-block">+ 添加板块</button>
                            <ul className="nav nav-pills flex-column" style={{ padding: '10px 0' }}>
                                {blocks}
                            </ul>
                        </nav>
                        <div className="col-9">
                            <button onClick={() => { this.props.history.push({ pathname: '/business/comm/add-' + this.state.shop.id }) }} className="btn btn-block btn-success">+ 添加商品</button>
                            {comms}
                        </div>
                    </div>
                </div>

                <div className="modal fade" id="modal-block">
                    <div className="modal-dialog">
                        <div className="modal-content">

                            <div className="modal-header">
                                <h4 className="modal-title">添加板块</h4>
                                <button type="button" className="close" data-dismiss="modal">&times;</button>
                            </div>

                            <div className="modal-body">
                                <input className="form-control" value={this.state.blockName} onChange={this.editBlockName} placeholder="板块名称"></input>
                            </div>
                            <div className="modal-footer">
                                <button type="button" className="btn btn-secondary" data-dismiss="modal">关闭</button>
                                <button type="button" className="btn btn-success" onClick={() => { this.addBlock() }}>提交</button>
                            </div>

                        </div>
                    </div>
                </div>
            </>
        );
    }
}

export class EditCommodity extends React.Component {
    constructor(props) {
        super(props)

        this.changeImage = this.changeImage.bind(this)
        this.defaultInit = this.defaultInit.bind(this)
        this.getIdByName = this.getIdByName.bind(this)
        this.getNameById = this.getNameById.bind(this)
        this.state = {
            method: (props.match.params.id.startsWith('add')) ? itemAdd : itemEdit,
            init: (props.match.params.id.startsWith('add')) ? this.defaultInit : itemGet,
            param: props.match.params.id,
            blocks: [],
            comm: {
                id: props.match.params.id,
                blockId: 0,
                shopId: 0,
                description: '',
                name: '',
                image: '',
                minQuantity: 1,
                packPrice: 0,
                price: 0,
                specifications: '[]'
            }
        }

    }

    defaultInit(_, result) {
        let id = this.state.param
        let shopId = id.substr(id.lastIndexOf('-') + 1)
        let comm = this.state.comm
        comm.shopId = shopId
        result(comm)
    }

    componentDidMount() {
        this.state.init(this.state.comm.id, (cdata) => {
            getShop(cdata.shopId, (sdata) => {
                this.setState({
                    blocks: sdata.blocks,
                    shopId: cdata.shopId,
                    comm: {
                        id: cdata.id,
                        blockId: cdata.blockId,
                        description: cdata.description,
                        name: cdata.name,
                        image: cdata.image,
                        minQuantity: cdata.minQuantity,
                        packPrice: cdata.packPrice,
                        price: cdata.price,
                        specifications: cdata.specifications
                    },
                    selblock: cdata.blockId
                })
            })
        })
    }

    changeImage(event) {
        let url = event.target.value

        this.setState((prevState, props) => {
            let comm = prevState.comm
            comm.image = url
            return {
                comm: comm
            }
        })
    }

    handleSubmit = (value, actions) => {
        let id = this.state.comm.id.toString()
        if (id.startsWith('add')) {
            id = id.substr(id.lastIndexOf('-') + 1)
        }

        let comm = {
            id: id,
            blockId: this.getIdByName(document.getElementById('sel-block').value),
            name: value.name,
            description: value.description,
            image: this.state.comm.image,
            price: value.price,
            packPrice: value.packPrice,
            minQuantity: value.minQuantity,
            specifications: value.specifications
        }

        this.state.method(comm)
        actions.setSubmitting(false)
    }

    getIdByName(name) {
        let result;

        this.state.blocks.forEach(b => {
            if (b.name == name) {
                result = b.id
            }
        });

        return result
    }

    getNameById(id) {
        let result;
        this.state.blocks.forEach(b => {
            if (b.id == id) {
                result = b.name
            }
        });

        return result
    }

    validateJSON(value) {
        // specifications: [ { name: "选规格", spec: { "微辣": 0.0, "不辣": 0.0, "加孜然": 0.5 } } ]

        let error
        try {
            let arr = JSON.parse(value)
            arr.forEach(s => {
                if (s.name && s.spec) {
                    let specs = s.spec
                    for (var key in specs) {
                        if (typeof specs[key] !== 'number' || isNaN(specs[key])) {
                            error = '无效的规格格式'
                        }
                    }
                } else {
                    error = '无效的规格格式'
                }
            })
        } catch (e) {
            error = '无效的规格格式'
            return error
        }

        return error
    }

    render() {
        let form;

        if (this.state.init == this.defaultInit) {
            // Empty
            form = <Formik
                onSubmit={this.handleSubmit}
                initialValues={this.state.comm}
                render={({ errors, status, touched, isSubmitting }) => (
                    <Form>
                        <div className="form-group">
                            <label htmlFor="name">商品名</label>
                            <Field className="form-control" id="name" name="name" type="text" required />
                        </div>
                        <div className="form-group">
                            <label htmlFor="sel-block">商品板块</label>
                            <select
                                className="form-control"
                                id="sel-block"
                                value={this.getNameById(this.state.selblock)}
                                onChange={(value) => {
                                    this.setState({
                                        selblock: this.getIdByName(value.target.value)
                                    })
                                }}>
                                {this.state.blocks.map(b => {
                                    return <option key={"option-" + b.id}>{b.name}</option>
                                })}
                            </select>
                        </div>
                        <div className="form-group">
                            <label htmlFor="image">商品图片</label>
                            <Field onChange={this.changeImage} className="form-control" id="image" name="image" type="text" value={this.state.comm.image} required />
                            <img src={this.state.comm.image} width="100px" height="100px"></img>
                        </div>
                        <div className="form-group">
                            <label htmlFor="description">商品描述</label>
                            <Field className="form-control" id="description" name="description" type="text" />
                        </div>
                        <div className="form-group">
                            <label htmlFor="price">价格</label>
                            <Field className="form-control" id="price" name="price" type="number" required />
                        </div>
                        <div className="form-group">
                            <label htmlFor="specifications">规格（JSON）</label>
                            <Field component="textarea" validate={this.validateJSON}
                                className="form-control" rows="10" id="specifications" name="specifications" type="text" required />
                            {errors.specifications && touched.specifications && (<div style={{ color: 'red' }}>{errors.specifications}</div>)}
                        </div>
                        <div className="form-group">
                            <label htmlFor="minQuantity">起售数量</label>
                            <Field className="form-control" id="minQuantity" name="minQuantity" type="number" required />
                        </div>
                        <div className="form-group">
                            <label htmlFor="packPrice">包装费</label>
                            <Field className="form-control" id="packPrice" name="packPrice" type="number" required />
                        </div>
                        <button type="submit" className="btn btn-lg btn-block btn-danger" disabled={isSubmitting}>提交</button>
                    </Form>
                )}
            />
        } else {
            if (this.state.comm.name) {
                form = <Formik
                    onSubmit={this.handleSubmit}
                    initialValues={this.state.comm}
                    render={({ errors, status, touched, isSubmitting }) => (
                        <Form>
                            <div className="form-group">
                                <label htmlFor="name">商品名</label>
                                <Field className="form-control" id="name" name="name" type="text" required />
                            </div>
                            <div className="form-group">
                                <label htmlFor="name">商品板块</label>
                                <select
                                    className="form-control"
                                    id="sel-block"
                                    value={this.getNameById(this.state.selblock)}
                                    onChange={(value) => {
                                        this.setState({
                                            selblock: this.getIdByName(value.target.value)
                                        })
                                    }}>
                                    {this.state.blocks.map(b => {
                                        return <option>{b.name}</option>
                                    })}
                                </select>
                            </div>
                            <div className="form-group">
                                <label htmlFor="image">商品图片</label>
                                <Field onChange={this.changeImage} className="form-control" id="image" name="image" type="text" value={this.state.comm.image} required />
                                <img src={this.state.comm.image} width="100px" height="100px"></img>
                            </div>
                            <div className="form-group">
                                <label htmlFor="description">商品描述</label>
                                <Field className="form-control" id="description" name="description" type="text" />
                            </div>
                            <div className="form-group">
                                <label htmlFor="price">价格</label>
                                <Field className="form-control" id="price" name="price" type="number" required />
                            </div>
                            <div className="form-group">
                                <label htmlFor="specifications">规格（JSON）</label>
                                <Field component="textarea" validate={this.validateJSON}
                                    className="form-control" rows="10" id="specifications" name="specifications" type="text" required />
                                {errors.specifications && touched.specifications && (<div style={{ color: 'red' }}>{errors.specifications}</div>)}
                            </div>
                            <div className="form-group">
                                <label htmlFor="minQuantity">起售数量</label>
                                <Field className="form-control" id="minQuantity" name="minQuantity" type="number" required />
                            </div>
                            <div className="form-group">
                                <label htmlFor="packPrice">包装费</label>
                                <Field className="form-control" id="packPrice" name="packPrice" type="number" required />
                            </div>
                            <button type="submit" className="btn btn-lg btn-block btn-danger" disabled={isSubmitting}>提交</button>
                        </Form>
                    )}
                />
            } else {
                form = ''
            }
        }

        return (
            <>
                <AppBar />
                <div className="container" id="container" style={{ padding: '20px 0' }}>
                    {form}
                </div>
            </>
        )
    }
}

export class AddShop extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            formData: {
                contact: '',
                name: '',
                desc: '',
                loc: '',
                lng: 0,
                lat: 0,
                licenseId: '',
                startPrice: 0,
                shipPrice: 0
            }
        }
        this.handlePosition = this.handlePosition.bind(this)
    }

    handleSubmit(contact, name, desc, loc, lng, lat, licenseId, startPrice, shipPrice) {
        newShop(contact, name, desc, loc, lng, lat, licenseId, startPrice, shipPrice)
    }

    handlePosition(data) {
        let poi = data
        this.setState((state, props) => {
            let d = state.formData
            try {

                d.loc = poi.address
                d.lng = Number.parseFloat(poi.location.substr(0, poi.location.indexOf(',')))
                d.lat = Number.parseFloat(poi.location.substr(poi.location.indexOf(',') + 1))

            } catch (error) {
                return {
                    formData: d
                }
            }
            return {
                formData: d
            }
        })
    }

    handleLoc(data) {
        this.setState((state, props) => {
            let d = state.formData

            d.loc = data
            return {
                formData: d
            }
        })
    }

    render() {
        return (
            <>
                <AppBar />
                <div className="container" style={{ padding: '15px 0' }}>
                    <Formik
                        onSubmit={(value, actions) => {
                            this.handleSubmit(
                                value.contact,
                                value.name,
                                value.desc,
                                this.state.formData.loc,
                                this.state.formData.lng,
                                this.state.formData.lat,
                                value.licenseId,
                                value.startPrice,
                                value.shipPrice
                            )
                            actions.setSubmitting(false)
                        }}
                        initialValues={this.state.formData}
                        render={({ errors, status, touched, isSubmitting }) => (
                            <Form>
                                <div className="form-group">
                                    <label htmlFor="name">店铺名称</label>
                                    <Field className="form-control" id="name" name="name" type="text" required />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="desc">店铺描述</label>
                                    <Field className="form-control" id="desc" name="desc" type="text" required />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="loc">店铺地理位置</label>
                                    <Field onChange={(value) => {
                                        this.handleLoc(value.target.value)
                                    }} className="form-control" id="loc" name="loc" type="text" value={this.state.formData.loc} required />
                                </div>
                                <SelectMap handlePosition={this.handlePosition} />
                                <div className="form-group">
                                    <label htmlFor="contact">店铺联系方式</label>
                                    <Field className="form-control" id="contact" name="contact" type="text" required />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="licenseId">营业许可证号</label>
                                    <Field className="form-control" id="licenseId" name="licenseId" type="text" required />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="startPrice">起送价</label>
                                    <Field className="form-control" id="startPrice" name="startPrice" type="number" required />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="shipPrice">配送费</label>
                                    <Field className="form-control" id="shipPrice" name="shipPrice" type="number" required />
                                </div>
                                <button type="submit" className="btn btn-lg btn-block btn-danger" disabled={isSubmitting}>注册</button>
                            </Form>
                        )}
                    />

                </div>
            </>
        )
    }
}